/*PersonProfile control class*/
$N.ctrl.HealthInputDataCtrl = (function () {
		var notify;
		var healthInputData = new Array();
		var selectedIndex = 0;

		function _sqlResponseCb(tx, result) {
			console.log("healthInputData.length = " + healthInputData.length);
			if (result.rowsAffected != 0) {

				console.log(result.rows.items(0));
			} else {
				console.log("no healthData is filled!");
			}
		}

		function _ajaxResponseCb(jsonResponse) {
			console.log(jsonResponse);
			if (jsonResponse.length == 0 || jsonResponse.search("FAILED") !== -1) {
				//put a placeholder
				console.log("json_response string is empty.");
			} else {
				if (jsonResponse.search("NO MORE") != -1) {
					return;
				}

				jsonObject = JSON.parse(jsonResponse);
				//save data into the database
				for (var i = 0; i < jsonObject.length; i++) {
					var data = jsonObject[i].HealthInputData;
					healthInputData.push(data);
					$N.databaseSet.HealthInputDataTable.addHealthInputData(data);
				}
			}
			notify(healthInputData);
		}

		function getHealthInputDataSuccessCb(tx, result, data) {
			console.log("get data successfully" + result);
			healthInputData.length = 0;
			if (result.rows.length != 0) {
				var i = 0;
				for ( i = 0; i < result.rows.length; i++) {
					healthInputData.push(result.rows.item(i));
				}
				notify(healthInputData);
			} else {/*nothing in local db*/
				console.log("getHealthInputData : personID = " + data);
				downloadHealthInputData(data);
			}
		}

		function insertDataIntoCore(data) {
			healthInputData.push(data);
			$N.databaseSet.HealthInputDataTable.addHealthInputData(data, _sqlResponseCb);
		}

		function downloadHealthInputData(personID) {
			var postURL = "http://localhost/cakephp/mobileUsersAdapter/downloadHealthInputData";
			var para = {
				jsonstring : JSON.stringify({
					personID : personID
				})
			};
			$N.util.ajaxPost(postURL, para, _ajaxResponseCb);
		}

		function getHealthInputData(personID) {
			var callbackObj = new Callback(personID, getHealthInputDataSuccessCb);
			$N.databaseSet.HealthInputDataTable.getHealthInputData(personID, callbackObj);
		}

		function registerClientNotify(notifyCb) {
			notify = notifyCb;
		}

		return {
			insertDataIntoCore : insertDataIntoCore,
			getHealthInputData : getHealthInputData,
			downloadHealthInputData : downloadHealthInputData,
			registerClientNotify : registerClientNotify,
			healthInputData : healthInputData
		};
	}());
